import requests
import re


class DownloadCrawler:

    def __init__(self, url):
        self.url = url
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36",
        }
        self.html = ""
        self.download_url = ""

    def get_data(self):
        try:
            response = requests.get(url=self.url, headers=self.headers)
            self.html = response.text
        except Exception as e:
            print(e)

    def parser_data(self):
        download_url = re.findall(r"window.mp3_url = '(.*?)'", self.html, re.S)
        if download_url:
            self.download_url = download_url[0]
            print(self.download_url)

    def download(self):
        try:
            response = requests.get(url=self.download_url, headers=self.headers)
            with open('my.mp3', 'ab') as f:
                f.write(response.content)
        except Exception as e:
            print(e)

    def run(self):
        self.get_data()
        self.parser_data()
        self.download()


def down(songs):
    spider = DownloadCrawler(url=songs[0])
    spider.run()


if __name__ == '__main__':
    songs = ['https://www.gequbao.com/music/62797', 'https://www.gequbao.com/music/62799', 'https://www.gequbao.com/music/62790', 'https://www.gequbao.com/music/62798', 'https://www.gequbao.com/music/62792', 'https://www.gequbao.com/music/62794', 'https://www.gequbao.com/music/62801', 'https://www.gequbao.com/music/62800', 'https://www.gequbao.com/music/62796', 'https://www.gequbao.com/music/101314']
    spider = DownloadCrawler(url=songs[0])
    spider.run()
